#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <string.h>
#include <linux/fd.h>
#include <sys/mount.h>
#include <scsi/scsi.h>
#include <scsi/sg.h>
#include <scsi/scsi_ioctl.h>

/*
 * 弹出U盘的代码
 */

int main(int argc, char ** argv)
{
    int fd = -1;
    char * device;
    int status, k;
    sg_io_hdr_t io_hdr;
    unsigned char allow_rm_blk[6] = {ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0};
    unsigned char start_stop1_blk[6] = {START_STOP, 0, 0, 0, 1, 0};
    unsigned char start_stop2_blk[6] = {START_STOP, 0, 0, 0, 2, 0};
    unsigned char inq_buff[2] ;
    unsigned char sense_buff[32];

    if (argc != 2) {
        printf("usage:u-eject -s /dev/sdb1 \n");
        return -1;
    }

    device = strdup(argv[1]);
    printf("device = %s\n", device);
    if ((fd = open(device, O_RDONLY|O_NONBLOCK)) < 0) {
        printf("open device %s failed!\n", device);
        free(device);
        return -1;
    }

    memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
    io_hdr.interface_id = 'S';
    io_hdr.cmd_len = 6;
    io_hdr.mx_sb_len = sizeof(sense_buff);
    io_hdr.dxfer_direction = SG_DXFER_NONE;
    io_hdr.dxfer_len = 0;
    io_hdr.dxferp = inq_buff;
    io_hdr.sbp = sense_buff;
    io_hdr.timeout = 10000;
    io_hdr.cmdp = allow_rm_blk;

    status = ioctl(fd, SG_IO, (void *) &io_hdr);
    if (status < 0) 
        goto out;

    io_hdr.cmdp = start_stop1_blk;
    status = ioctl(fd, SG_IO, (void *) &io_hdr);
    if (status < 0)
        goto out;

    io_hdr.cmdp = start_stop2_blk;
    status = ioctl(fd, SG_IO, (void *) &io_hdr);
    if (status < 0)
        goto out;

    status = ioctl(fd, BLKRRPART);

out:
    close(fd);
    free(device);

    return 0;
}
